package com.fy.utilsproject.utils.math;

import com.fy.utilsproject.utils.math.entity.TwoDimensionalCoordinate;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * 一次函数：y = kx + b
 */
public class PrimaryFunction {

    //斜率
    private double k;
    private double b;
    private List<TwoDimensionalCoordinate> coordinateList = new ArrayList<>();

    public double getK() {
        return k;
    }

    public PrimaryFunction setK(double k) {
        this.k = k;
        return this;
    }

    public double getB() {
        return b;
    }

    public PrimaryFunction setB(double b) {
        this.b = b;
        return this;
    }

    /**
     * 添加坐标点
     *
     * @param x X轴坐标
     * @param y Y轴坐标
     */
    public PrimaryFunction addCoordinate(double x, double y) {
        coordinateList.add(new TwoDimensionalCoordinate(x, y));
        return this;
    }

    /**
     * 添加坐标点
     *
     * @param coordinate 二维坐标
     */
    public PrimaryFunction addCoordinate(TwoDimensionalCoordinate coordinate) {
        coordinateList.add(coordinate);
        return this;
    }

    public boolean calculation() {
        if (coordinateList.size() == 2) {
            //如果集合中已经保存了两个坐标点则取这两个坐标点进行计算
            TwoDimensionalCoordinate coordinate1 = coordinateList.get(0);
            TwoDimensionalCoordinate coordinate2 = coordinateList.get(1);
            if (coordinate1.x == coordinate2.x) {
                return false;
            }
            k = (coordinate2.y - coordinate1.y) / (coordinate2.x - coordinate1.x);
            b = coordinate1.y - coordinate1.x * k;
            return true;
        } else if (coordinateList.size() > 2) {
            //如果集合中的坐标点数量大于2则计算近似解
        }
        return false;
    }

    public double getY(double x) {
        return x * k + b;
    }

    public double getX(double y) {
        return Double.parseDouble(new DecimalFormat("0.000000000").format((y - b) / k));
    }

}
